﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace HttpCore
{
    public class AsyncHttp
    {
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        byte[] byteArray;
        public AsyncHttp()
        {

        }
        /// <summary>
        /// 异步获取Cookies
        /// </summary>
        /// <param name="_url"></param>
        /// <param name="paramData"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string GetLoginCookies(string _url, string paramData, Encoding encoding)
        {
            CookieCollection cookiecollection = new CookieCollection();
            HttpWebRequest httpwebrequest = HttpWebRequest.Create(_url) as HttpWebRequest;
            httpwebrequest.CookieContainer = new CookieContainer();
            httpwebrequest.CookieContainer.Add(cookiecollection);
            byteArray = encoding.GetBytes(paramData);
            httpwebrequest.Method = "POST";
            httpwebrequest.ContentType = "application/x-www-form-urlencoded";
            httpwebrequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
            httpwebrequest.Accept = "text/html, application/xhtml+xml, */*";
            httpwebrequest.Referer = "http://oa.hdsxtech.com:8080/general/";
            httpwebrequest.ContentLength = byteArray.Length;
            //异步请求
            httpwebrequest.BeginGetRequestStream(new AsyncCallback(HttpRequestStreamCallback), httpwebrequest);
            //线程等待
            allDone.WaitOne();

            //获取Response
            HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, encoding);
            string responseString = streamRead.ReadToEnd();

            streamResponse.Close();
            streamRead.Close();

            response.Close();
            if (responseString.IndexOf("正在进入OA系统，请稍候") != -1)
            {
                responseString = httpwebrequest.CookieContainer.GetCookieHeader(httpwebrequest.RequestUri);
            }
            else
            {
                responseString = string.Empty;
            }
            return responseString;
        }
        private void HttpRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
            allDone.Set();
        }


        #region 异步操作
        /// <summary>
        /// 执行URL请求异步
        /// </summary>
        /// <param name="_url"></param>
        /// <param name="_cookie"></param>
        /// <returns></returns>
        public string OARequestGet(string _url, string _cookie)
        {
            //创建一个新的 HttpWebRequest 对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            //设置ContentType属性mime
            request.ContentType = "application/x-www-form-urlencoded";
            //设置请求的方法
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.Referer = "http://oa.hdsxtech.com:8080/general/";
            request.Headers.Add("Cookie", _cookie);
            //开始异步操作
            //request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
            //request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
            //阻止本次线程
            //allDone.WaitOne();

            //获取Response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse,Encoding.Default);
            string responseString = streamRead.ReadToEnd();
            streamResponse.Close();
            streamRead.Close();
            response.Close();
            return responseString;
        }
        #endregion
        #region 异步POST请求
        public string OARequestPost(string _url,string paraData,string cookie,Encoding encoding)
        {
            //创建一个新的 HttpWebRequest 对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            //设置ContentType属性mime
            request.ContentType = "application/x-www-form-urlencoded";
            //设置请求的方法
            request.Method = "POST";
            byteArray = encoding.GetBytes(paraData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.Referer = "http://oa.hdsxtech.com:8080/general/";
            request.Headers.Add("Cookie", cookie);
            //开始异步操作
            request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
            //阻止本次线程
            allDone.WaitOne();

            //获取Response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse,encoding);
            string responseString = streamRead.ReadToEnd();

            streamResponse.Close();
            streamRead.Close();

            response.Close();
            return responseString;
        }
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
            allDone.Set();
        }
        #endregion
    }
}
